import math


class Enemy:
    images = []

    def __init__(self, width=64, height=64):
        self.path = [(7, 259), (82, 257), (178, 268), (230, 308), (299, 312), (370, 314), (435, 312), (493, 313),
                     (551, 305), (600, 263), (616, 197), (635, 130), (688, 86), (763, 74), (810, 130), (828, 194),
                     (844, 246), (880, 292), (937, 319), (991, 344), (1029, 397), (1032, 463), (1013, 520), (948, 556),
                     (864, 566), (790, 568), (725, 587), (648, 623), (565, 633), (490, 633), (415, 632), (317, 635),
                     (249, 632), (158, 614), (109, 573), (86, 500), (66, 429), (14, 388), (-50, 388)]
        self.x = self.path[0][0]
        self.y = self.path[0][1]
        self.health = 1
        self.animation_count = 0
        self.img = None
        self.width = width
        self.height = height
        self.vel = 10   # 速度
        self.path_pos = 1
        self.move_count = 0
        self.move_step_dis = 1   # 行走的单位距离

    def draw(self, win):
        """
        Draw the enemy with the given image
        :param win: surface
        :return: None
        """
        self.animation_count += 1
        if self.animation_count >= len(self.images):
            self.animation_count = 0
        self.img = self.images[self.animation_count]
        win.blit(self.img, (self.x - self.width / 2, self.y - self.height / 2))
        self.move()

    def collide(self, x, y):
        """
        Return if position has hit enemy
        """
        return x <= self.x + self.width and x >= self.x and y <= self.y + self.height and y >= self.y

    def move(self):
        """
        move enemy
        """

        x1, y1 = self.path[self.path_pos]

        # 每次行走的距离
        step = self.move_step_dis * self.vel

        # 离下一个 path pos 的距离
        distance_next_pos = math.sqrt((x1 - self.x) ** 2 + (y1 - self.y) ** 2)

        if distance_next_pos <= step:
            self.x = x1
            self.y = y1
            self.path_pos += 1
        else:
            w = step / distance_next_pos
            self.x += (x1 - self.x) * w
            self.y += (y1 - self.y) * w

    def hit(self):
        """
        return true if enemy is died
        """
        self.health -= 1
        if self.health <= 0:
            return True
